package com.DHH.Shiro;

import com.DHH.Entity.Base.BaseLoginRecord;
import com.DHH.Entity.Base.BaseRole;
import com.DHH.Entity.Base.BaseUser;
import com.DHH.Mapper.Base.BaseLoginRecordMapper;
import com.DHH.Mapper.Base.BaseRoleMapper;
import com.DHH.Mapper.Base.BaseUserMapper;
import com.DHH.Service.Base.IBaseLoginRecordService;
import com.DHH.Util.MyUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * Created by Administrator on 2017/1/11.
 */
@Service
@Transactional
public class MyShiro extends AuthorizingRealm {

    @Autowired
    private BaseUserMapper baseUserMapper;
    @Autowired
    private BaseRoleMapper baseRoleMapper;
    /**
     * 权限认证
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 从 principals获取主身份信息
        // 将getPrimaryPrincipal方法返回值转为真实身份类型（在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型），
        String username = (String) principals.getPrimaryPrincipal();
        BaseUser user =new BaseUser();
        user.setIdentity(username);
        user=baseUserMapper.selectOne(user);
        BaseRole baseRole=new BaseRole();

      /*  List<BaseRole> list=baseRoleMapper.select(user);*/
        Set<String> shiroRoles=new HashSet<String>() ;//shiro所需要的角色
      /*  for (SysRole sysRole:
                list) {
            shiroRoles.add(sysRole.getRoleMark());
        }*/
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRoles(shiroRoles);
        return info;
    }

    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        BaseUser user=new BaseUser();
        user.setIdentity(token.getUsername());
        //查出是否有此用户
        user = baseUserMapper.selectOne(user);
        if(user!=null){
                return new SimpleAuthenticationInfo(user.getIdentity(),user.getToken(), getName());
        }
        return null;
    }
 }
